const app = getApp()
var QR = require("../../utils/qrcode.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navH: app.data.navHeight,
    windowHeight: app.data.windowHeight,
    heifht: '',
    host: app.data.host,
    info: wx.getStorageSync('vs-info'),
    isShowBill: false,
    isAuth: true,
    url: "",
    certificateData: wx.getStorageSync('vs-info'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      certificateData: wx.getStorageSync('vs-info')
    })
    let w = app.getRatio();
    let heifht = (app.data.windowHeight - app.data.navHeight - 902 / 2 * w) / 2 + 4;
    this.setData({
      heifht: heifht
    })
    var left = this;
    if (app.data.jsonPage) {
      var nvabarData = {
        title: '分享好友',
        bgclase: true,
        showCapsule: true
      };
      this.setData({
        pageToconfigure: '分享好友',
        nvabarData: nvabarData,
      });
    } else {
      app.getjsonPage = res => {
        var nvabarData = {
          title: res.sharePostere.title,
          bgclase: true,
          showCapsule: true
        };
        left.setData({
          pageToconfigure: res.sharePostere,
          nvabarData: nvabarData,
        });
      };
    }
    wx.showLoading({
      title: '正在加载中',
      mask: false
    })
    this.qrcode()
    this.settings()
  },
  // subTap: function () {
  //   let that = this;
  //   wx.requestSubscribeMessage({
  //     tmplIds: ['TEtCC1267hiVi0rkpi4tDEh3yEshyVKFDuPL9UwKunA'],
  //     success(res) {
  //       console.log(res)
  //       // that.setData({
  //       //   textcontent: '提示：授权成功'
  //       // })
  //     },
  //     fail(res) {
  //       // that.setData({
  //       //   textcontent: '提示：授权失败'
  //       // })
  //     }
  //   })
  // },
  settings() {
    wx.$.fetch('/api/settings', {
      method: 'get',
      data: {
        type: 'mini_template'
    }
    }).then(res => {
      // console.log(res)
    })
  },
  myCatchTouch() {
    return
  },
  qrcode() {
    // console.log(this.data.info.id)
    wx.$.fetch('api/member/qrcode', {
      hideLoading: true,
      method: 'get',
      data: {
        path: "pages/home/home?recommend_id=" + this.data.info.id
      }
    }).then(res => {
      // console.log(res)
      if (res.data.code == 200) {
        this.setData({
          url: res.data.data
        })
        this.sharePosteCanvas(res.data.data)
      } else {
        wx.hideLoading();
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 1000
        })
      }
    })
  },
  sharePosteCanvas(url) {  // 开始生成海报
    wx.showLoading({
      title: '正在加载中',
      mask: false
    })
    const wxGetImageInfo = app.promisify(wx.getImageInfo);
    var lefts = this;
    let dataurl = url;
    console.log(wx.getStorageSync('vs-info').avatar);
    let avatar = wx.getStorageSync('vs-info').avatar.replace(/http:\/\//i, "https://");
    avatar = avatar == '' ?  'https://vstartup-1253985024.cos.ap-beijing.myqcloud.com/zxstest/images/card/200729/18cbf1a9f26027294b90ecb0854f025108b90320.jpeg' : avatar
    Promise.all([
      wxGetImageInfo({ //头像
        src: avatar,
      }),
      wxGetImageInfo({ //背景图
        src: 'https://vstartup-1253985024.cos.ap-beijing.myqcloud.com/zxs/poster_content_bg.png'
      }),
      wxGetImageInfo({ //二维码
        src: dataurl
      })
    ]).then(res => {
      var w = app.getRatio();
      var ctx = wx.createCanvasContext('application');
      lefts.draw(ctx, res, lefts, w);
    }).catch(res => {
      // console.log(res)
      wx.hideLoading();
      wx.showToast({
        title: '证书加载失败请重新加载',
        icon: 'none',
        duration: 1000
      })
    })
  },
  draw(ctx, res, lefts, w) {
    // 底图
    ctx.drawImage(res[1].path, 0, 0, 620 / 2 * w, 902 / 2 * w);
    // 小程序码
    ctx.drawImage(res[2].path, 90 / 2 * w, 660 / 2 * w, 145 / 2 * w, 151 / 2 * w);
    //头像
    ctx.save();
    ctx.beginPath();
    ctx.arc(112 / 2 * w, 300 / 2 * w, 37 / 2 * w, 0, Math.PI * 2, false);
    ctx.clip();
    ctx.drawImage(res[0].path, 75 / 2 * w, 263 / 2 * w, 74 / 2 * w, 74 / 2 * w);
    ctx.restore();
    ctx.closePath()

    // 姓名
    var username = lefts.data.certificateData.nickname;
    username = username.length > 15 ? username.substring(0, 8) + '...' : username;
    ctx.setFillStyle('#222222') // 文字颜色
    var zihao = 30 / 2 * w;
    ctx.setFontSize(zihao); // 文字字号
    ctx.fillText(username, 180 / 2 * w, 298 / 2 * w, 400 / 2 * w);

    ctx.setFillStyle('#999999') // 文字颜色
    var zihao = 24 / 2 * w;
    ctx.setFontSize(zihao); // 文字字号 
    ctx.fillText('这个自习室很棒，快来看看吧 ~', 180 / 2 * w, 336 / 2 * w, 400 / 2 * w);

    // 介绍
    ctx.setFillStyle('#000000') // 文字颜色
    var zihao = 42 / 2 * w;
    ctx.setFontSize(zihao); // 文字字号
    ctx.fillText('默耕自习室', 205 / 2 * w, 445 / 2 * w, 400 / 2 * w);

    // 介绍
    ctx.setFillStyle('#666666') // 文字颜色
    var zihao = 24 / 2 * w;
    ctx.setFontSize(zihao); // 文字字号
    var company_name = '享受安静、美好空间';
    ctx.fillText(company_name, 111 / 2 * w, 528 / 2 * w, 400 / 2 * w);
    // 介绍
    var company_name = '共享自习室，共享时光';
    ctx.fillText(company_name, 111 / 2 * w, 574 / 2 * w, 400 / 2 * w);
    //小图标
    ctx.drawImage('../../images/icon/poster_content_icon_finger.png', 264 / 2 * w, 669 / 2 * w, 76 / 2 * w, 68 / 2 * w);
    // 介绍
    ctx.setFillStyle('#222222') // 文字颜色
    var zihao = 22 / 2 * w;
    ctx.setFontSize(zihao); // 文字字号
    var company_name = '长按识别小程序码';
    ctx.fillText(company_name, 272 / 2 * w, 776 / 2 * w, 400 / 2 * w);
    var company_name = '即可享受';
    ctx.fillText(company_name, 272 / 2 * w, 818 / 2 * w, 400 / 2 * w);
    let distance = 272 / 2 * w + ctx.measureText(company_name).width;
    ctx.setFillStyle('#FF4A00') // 文字颜色
    ctx.fillText('自习室折扣会员卡', distance, 818 / 2 * w, 400 / 2 * w);
    ctx.draw(false, function () {
      lefts.setData({
        isShowBill: false
      })
      wx.hideLoading();
    });
  },
  leftOfCalculation(width, text, ctx, w, type) { //计算靠左的距离
    var textwidt = ctx.measureText(text).width;
    var widths = type ? width / 2 * w / 2 : width / 2 * w;
    var distance = widths - textwidt / 2;
    return distance;
  },

  //保存图片
  saveimg() {
    let that = this
    //若二维码未加载完毕，加个动画提高用户体验
    wx.getSetting({
      success(res) {
        //没有权限，发起授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success(res) { //用户允许授权，保存图片到相册
              that.submission();
            },
            fail(res) { //用户点击拒绝授权，跳转到设置页，引导用户授权
              that.setData({
                isAuth: false
              })
            }
          })
        } else { //用户已授权，保存到相册
          that.submission();
        }
      }
    });
  },
  preservationImg2() {
    var that = this;
    wx.openSetting({
      success() {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success() {
            that.setData({
              isAuth: true
            })
            that.submission();
          }
        })
      }
    })
  },
  //下载图片地址并保存到相册，提示保存成功
  submission() {
    const wxCanvasToTempFilePath = app.promisify(wx.canvasToTempFilePath);
    const wxSaveImageToPhotosAlbum = app.promisify(wx.saveImageToPhotosAlbum);
    var left = this;
    wxCanvasToTempFilePath({
      canvasId: 'application'
    }, this).then(res => {
      return wxSaveImageToPhotosAlbum({
        filePath: res.tempFilePath
      })
    }).then(res => {
      wx.showToast({
        title: '已保存到相册'
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      certificateData: wx.getStorageSync('vs-info')
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    let certificateData = that.data.certificateData;
    return {
      title: certificateData.nickname + '分享给您的折扣卡',
      path: "pages/home/home?recommend_id=" + certificateData.id,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    };
  }
})